﻿using System;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using PivotalTrackerAPI.Domain.Model;

namespace PivotalTrackerAPI.Domain.Services
{
    public class PivotalService
    {
        public PivotalService(string token) 
        {
            Token = token;
            SaveToXml = false;
        }

        public PivotalService(string token, string projectId) 
        {
            Token = token;
            ProjectId = projectId;
            SaveToXml = false;
        }

        public bool SaveToXml
        {
            get;
            set;
        }

        public string Token 
        {
            get; set;
        }

        public string ProjectId
        {
            get;
            set;
        }

        public string StoryXmlDirectory { get; set; }

        public string AddStory(PivotalStory story)
        {
            string url = "http://www.pivotaltracker.com/services/v3/projects/" + ProjectId + "/stories?token=" + Token;

            string storyXml = "<story><story_type>" + story.StoryType + "</story_type><name>" + story.Name + "</name><requested_by>" + story.Requestor + "</requested_by>";
            if (!string.IsNullOrEmpty(story.Description)) storyXml += "<description>" + story.Description + "</description>";
            storyXml += "</story>";

            return AddStoryOrTask(url, storyXml);
        }

        public string AddTask(string storyId, string description)
        {
            string url = "http://www.pivotaltracker.com/services/v3/projects/" + ProjectId + "/stories/" + storyId + "/tasks?token=" + Token;

            string task = "<task><description>" + description + "</description></task>";

            return AddStoryOrTask(url, task);
        }

        public string AddNote()
        {
            //
            return "";
        }

        private string AddStoryOrTask(string url, string data)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            // Set the ContentType property.
            request.ContentType = "application/xml";

            // Set the Method property to 'POST' to post data to the URI.
            request.Method = "POST";
            request.Proxy = WebProxy.GetDefaultProxy();
            byte[] byteArray = Encoding.UTF8.GetBytes(data);
            request.ContentLength = byteArray.Length;

            try
            {
                Stream dataStream = request.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);

                dataStream.Close();
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

            Stream objStream;

            try
            {
                objStream = request.GetResponse().GetResponseStream();
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

            StreamReader objReader = new StreamReader(objStream);

            string sLine = "";
            int i = 0;
            StringBuilder sb = new StringBuilder();

            while (sLine != null)
            {
                i++;
                sLine = objReader.ReadLine();
                if (sLine != null)
                {
                    sb.Append(sLine); //Console.WriteLine("{0}:{1}", i, sLine);
                }
            }
            //Console.ReadLine();
            
            string xml = sb.ToString();
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(xml);

            if (SaveToXml)
            {
                xmlDoc.Save(StoryXmlDirectory);
            }

            XmlNode urlNode = xmlDoc.SelectSingleNode("/story/url");
            return "Pivotal story created: " + urlNode.FirstChild.InnerText ?? "(couldn't load url)";
        }

        public XmlDocument GetStories(string project)
        {

            string url = "http://www.pivotaltracker.com/services/v3/projects/" + ProjectId + "/stories?token=" + Token;

            var uri = new Uri(url);

            // Create a new HttpWebRequest object.
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

            request.Proxy = WebProxy.GetDefaultProxy();

            Stream objStream;
            objStream = request.GetResponse().GetResponseStream();

            StreamReader objReader = new StreamReader(objStream);

            string sLine = "";
            int i = 0;
            StringBuilder sb = new StringBuilder();

            while (sLine != null)
            {
                i++;
                sLine = objReader.ReadLine();
                if (sLine != null)
                {
                    Console.WriteLine("{0}:{1}", i, sLine);
                    sb.Append(sLine);
                }

            }
            Console.ReadLine();

            string xml = sb.ToString();

            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.LoadXml(xml);

            xmlDoc.Save(StoryXmlDirectory);

            StreamReader str = new StreamReader(StoryXmlDirectory);
            XmlSerializer xSerializer = new XmlSerializer(typeof(PivotalStory));

            PivotalStory myStories = (PivotalStory)xSerializer.Deserialize(str);

            //foreach (storiesStory story in myStories.story)
            //{
            //    Debug.Write(string.Format("Name: {0} {1}", story.name, Environment.NewLine));
            //    Debug.Write(string.Format("Description: {0} {1}", story.description, Environment.NewLine));
            //    Debug.Write(Environment.NewLine);

            //}

            str.Close();

            return null;

        }
    }
}
